package com.ibr.ticketmanagement.app.util;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.ibr.ticketmanagement.app.data.ActionPlan;
import com.ibr.ticketmanagement.app.data.FEReport;
import com.ibr.ticketmanagement.app.data.Location;
import com.ibr.ticketmanagement.app.data.LocationPart;
import com.ibr.ticketmanagement.app.data.Part;

import java.util.ArrayList;
import java.util.List;

public class DatabaseHandler extends SQLiteOpenHelper {

    // Action Plan Table Columns names
    public static final String KEY_AP_ID = "id";
    public static final String KEY_AP_TICKET_ID = "ticket_id";
    public static final String KEY_AP_ACTION_ID = "action_id";
    public static final String KEY_AP_NAME = "name";
    public static final String KEY_AP_ACTION_PLAN = "action_plan";
    public static final String KEY_AP_WWSTART = "ww_start";
    public static final String KEY_AP_SITE_CONTACT = "site_contact";
    public static final String KEY_AP_SITE_ACCESS = "site_access";
    public static final String KEY_FE_REPORT_CREATED = "fe_report_created";
    public static final String KEY_AP_ORDER = "ap_order";
    // FE Report Table Columns names
    public static final String KEY_FE_ID = "id";

    public static final String KEY_FE_TICKET_ID = "ticket_id";
    public static final String KEY_FE_ACTION_PLAN = "action_plan_id";
    public static final String KEY_FE_FIELD_ENGINEER_ID = "field_engineer_id";
    public static final String KEY_FE_WORK_WINDOW = "work_window";
    public static final String KEY_FE_TIME_START = "time_start";
    public static final String KEY_FE_TIME_FINISHED = "time_finished";
    public static final String KEY_FE_SENT = "sent";
    public static final String KEY_FE_WORK_DONE = "work_done_value";
    public static final String KEY_FE_BILLABLE = "billable_value";
    public static final String KEY_FE_CLOSED = "closed_value";
    public static final String KEY_FE_TIME_TRAVEL = "time_travel_value";
    public static final String KEY_FE_MILES = "miles_value";
    public static final String KEY_FE_NUMBER_01 = "numberPicker_01_value";
    public static final String KEY_FE_PART_01 = "part_01_value";
    public static final String KEY_FE_LOCATION_01 = "location_01_value";
    public static final String KEY_FE_NUMBER_02 = "numberPicker_02_value";
    public static final String KEY_FE_PART_02 = "part_02_value";
    public static final String KEY_FE_LOCATION_02 = "location_02_value";
    public static final String KEY_FE_NUMBER_03 = "numberPicker_03_value";
    public static final String KEY_FE_PART_03 = "part_03_value";
    public static final String KEY_FE_LOCATION_03 = "location_03_value";
    public static final String KEY_FE_NUMBER_04 = "numberPicker_04_value";
    public static final String KEY_FE_PART_04 = "part_04_value";
    public static final String KEY_FE_LOCATION_04 = "location_04_value";
    // Location Table Columns names
    public static final String KEY_LOCATION_ID = "id";
    public static final String KEY_LOCATION_LOC_ID = "location_id";
    public static final String KEY_LOCATION_NAME = "location_name";
    public static final String KEY_LOCATION_VERSION = "version";
    // Part Table Columns names
    public static final String KEY_PART_ID = "id";
    public static final String KEY_PART_PART_ID = "part_id";
    public static final String KEY_PART_NAME = "part_name";
    // Location Part Table Columns names
    public static final String KEY_LOCATION_PART_ID = "id";
    public static final String KEY_LOCATION_PART_LOC_ID = "location_id";
    public static final String KEY_LOCATION_PART_PART_ID = "part_id";
    public static final String KEY_LOCATION_PART_QUANTITY = "quantity";
    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "ibrReport";
    // Contacts table name
    private static final String TABLE_ACTION_PLAN = "action_plan";
    private static final String TABLE_FE_REPORT = "fe_report";
    private static final String TABLE_LOCATION = "location";
    private static final String TABLE_PART = "part";
    private static final String TABLE_LOCATION_PART = "location_part";
    private static final String TAG = "DATABASE_HANDLER";


    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void init(Context context) {
        new DatabaseHandler(context).onUpgrade(this.getWritableDatabase(), 1, 1);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_ACTION_PLAN_TABLE = "CREATE TABLE " + TABLE_ACTION_PLAN + "("
                + KEY_AP_ID + " INTEGER PRIMARY KEY,"
                + KEY_AP_TICKET_ID + " INTEGER,"
                + KEY_AP_ACTION_ID + " INTEGER,"
                + KEY_AP_NAME + " TEXT,"
                + KEY_AP_ACTION_PLAN + " TEXT,"
                + KEY_AP_WWSTART + " TEXT,"
                + KEY_AP_SITE_CONTACT + " TEXT,"
                + KEY_AP_SITE_ACCESS + " TEXT,"
                + KEY_FE_REPORT_CREATED + " TEXT,"
                + KEY_AP_ORDER + " LONG" + ")";
        db.execSQL(CREATE_ACTION_PLAN_TABLE);

        String CREATE_FE_REPORT_TABLE = "CREATE TABLE " + TABLE_FE_REPORT + "("
                + KEY_FE_ID + " INTEGER PRIMARY KEY," + KEY_FE_TICKET_ID + " TEXT,"
                + KEY_FE_ACTION_PLAN + " TEXT,"
                + KEY_FE_FIELD_ENGINEER_ID + " TEXT,"
                + KEY_FE_WORK_WINDOW + " TEXT,"
                + KEY_FE_TIME_START + " TEXT,"
                + KEY_FE_TIME_FINISHED + " TEXT,"
                + KEY_FE_WORK_DONE + " TEXT,"
                + KEY_FE_BILLABLE + " TEXT,"
                + KEY_FE_CLOSED + " TEXT,"
                + KEY_FE_TIME_TRAVEL + " TEXT,"
                + KEY_FE_MILES + " TEXT,"
                + KEY_FE_NUMBER_01 + " INTEGER,"
                + KEY_FE_PART_01 + " TEXT,"
                + KEY_FE_LOCATION_01 + " TEXT,"
                + KEY_FE_NUMBER_02 + " INTEGER,"
                + KEY_FE_PART_02 + " TEXT,"
                + KEY_FE_LOCATION_02 + " TEXT,"
                + KEY_FE_NUMBER_03 + " INTEGER,"
                + KEY_FE_PART_03 + " TEXT,"
                + KEY_FE_LOCATION_03 + " TEXT,"
                + KEY_FE_NUMBER_04 + " INTEGER,"
                + KEY_FE_PART_04 + " TEXT,"
                + KEY_FE_LOCATION_04 + " TEXT,"
                + KEY_FE_SENT + " TEXT" + ")";
        db.execSQL(CREATE_FE_REPORT_TABLE);

        String CREATE_LOCATION_TABLE = "CREATE TABLE " + TABLE_LOCATION + "("
                + KEY_LOCATION_ID + " LONG PRIMARY KEY," + KEY_LOCATION_LOC_ID + " TEXT,"
                + KEY_LOCATION_NAME + " TEXT,"
                + KEY_LOCATION_VERSION + " LONG)";
        db.execSQL(CREATE_LOCATION_TABLE);

        String CREATE_PART_TABLE = "CREATE TABLE " + TABLE_PART + "("
                + KEY_PART_ID + " LONG PRIMARY KEY," + KEY_PART_PART_ID + " TEXT,"
                + KEY_PART_NAME + " TEXT)";
        db.execSQL(CREATE_PART_TABLE);

        String CREATE_LOCATION_PART_TABLE = "CREATE TABLE " + TABLE_LOCATION_PART + "("
                + KEY_LOCATION_PART_ID + " INTEGER PRIMARY KEY," + KEY_LOCATION_PART_LOC_ID + " LONG,"
                + KEY_LOCATION_PART_PART_ID + " LONG,"
                + KEY_LOCATION_PART_QUANTITY + " INTEGER)";
        db.execSQL(CREATE_LOCATION_PART_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACTION_PLAN);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_FE_REPORT);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATION);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_PART);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATION_PART);
        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new FEReport
    void addFEReport(FEReport feReport) {
        SQLiteDatabase db = this.getWritableDatabase();
        // Inserting Row
        db.insert(TABLE_FE_REPORT, null, feReport.getContentValues());
        db.close(); // Closing database connection
    }

    // Adding new ActionPlan
    void addActionPlan(ActionPlan actionPlan) {
        SQLiteDatabase db = this.getWritableDatabase();
        // Inserting Row
        db.insert(TABLE_ACTION_PLAN, null, actionPlan.getContentValues());
        db.close(); // Closing database connection
    }

    // Getting single FEReport
    FEReport getFEReport(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_FE_REPORT, new String[]{KEY_FE_ID, KEY_FE_TICKET_ID, KEY_FE_ACTION_PLAN,
                        KEY_FE_FIELD_ENGINEER_ID, KEY_FE_WORK_WINDOW, KEY_FE_TIME_START, KEY_FE_TIME_FINISHED,
                        KEY_FE_WORK_DONE, KEY_FE_BILLABLE, KEY_FE_CLOSED, KEY_FE_TIME_TRAVEL,
                        KEY_FE_MILES, KEY_FE_NUMBER_01, KEY_FE_PART_01, KEY_FE_LOCATION_01, KEY_FE_NUMBER_02,
                        KEY_FE_PART_02, KEY_FE_LOCATION_02, KEY_FE_NUMBER_03, KEY_FE_PART_03, KEY_FE_LOCATION_03,
                        KEY_FE_NUMBER_04, KEY_FE_PART_04, KEY_FE_LOCATION_04, KEY_FE_SENT}, KEY_FE_ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null
        );
        if (cursor != null && cursor.getCount() != 0) {
            cursor.moveToFirst();
        } else {
            return null;
        }
        try {
            return formFEReport(cursor);
        } finally {
            cursor.close();
        }
    }

    // Getting single ActionPlan
    ActionPlan getActionPlan(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_ACTION_PLAN, new String[]{KEY_AP_ID,
                        KEY_AP_TICKET_ID, KEY_AP_ACTION_ID, KEY_AP_NAME,
                        KEY_AP_WWSTART, KEY_AP_ACTION_PLAN,
                        KEY_AP_SITE_CONTACT, KEY_AP_SITE_ACCESS, KEY_FE_REPORT_CREATED, KEY_AP_ORDER}, KEY_AP_ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null
        );
        if (cursor != null && cursor.getCount() != 0) {
            cursor.moveToFirst();
        } else {
            return null;
        }
        try {
            return formActionPlan(cursor);
        } finally {
            cursor.close();
        }
    }

    private FEReport formFEReport(Cursor cursor) {
        return new FEReport(Integer.parseInt(cursor.getString(0)),
                Integer.parseInt(cursor.getString(1)),
                Integer.parseInt(cursor.getString(2)),
                Integer.parseInt(cursor.getString(3)),
                cursor.getString(4),
                cursor.getString(5),
                cursor.getString(6),
                cursor.getString(7),
                Boolean.valueOf(cursor.getString(8)),
                Boolean.valueOf(cursor.getString(9)),
                cursor.getString(10),
                cursor.getString(11),
                cursor.getInt(12),
                cursor.getString(13),
                cursor.getString(14),
                cursor.getInt(15),
                cursor.getString(16),
                cursor.getString(17),
                cursor.getInt(18),
                cursor.getString(19),
                cursor.getString(20),
                cursor.getInt(21),
                cursor.getString(22),
                cursor.getString(23),
                Boolean.valueOf(cursor.getString(24)));
    }

    private ActionPlan formActionPlan(Cursor cursor) {
        if (cursor == null || cursor.getCount() == 0) return null;
        return new ActionPlan(cursor.getInt(0),
                cursor.getInt(1),
                cursor.getInt(2),
                cursor.getString(3),
                cursor.getString(4),
                cursor.getString(5),
                cursor.getString(6),
                cursor.getString(7),
                Boolean.valueOf(cursor.getString(8)),
                cursor.getLong(9));
    }

    // Getting All FEReports
    public List<FEReport> getAllFEReports() {
        List<FEReport> feReportList = new ArrayList<FEReport>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_FE_REPORT;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor != null && cursor.getCount() != 0) {
            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    feReportList.add(formFEReport(cursor));
                } while (cursor.moveToNext());
            }
        }
        try {
            return feReportList;
        } finally {
            cursor.close();
        }
    }

    // Getting All ActionPlan
    public List<ActionPlan> getAllActionPlans() {
        List<ActionPlan> actionPlanList = new ArrayList<ActionPlan>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_ACTION_PLAN;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor != null && cursor.getCount() != 0) {
            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    actionPlanList.add(formActionPlan(cursor));
                } while (cursor.moveToNext());
            }
        }
        try {
            return actionPlanList;
        } finally {
            cursor.close();
        }
    }

    // Updating single FEReport
    public int updateFEReport(FEReport feReport) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {        // updating row
            return db.update(TABLE_FE_REPORT, feReport.getContentValues(), KEY_FE_ID + " = ?",
                    new String[]{String.valueOf(feReport.get_id())});
        } finally {
            db.close();
        }
    }

    // Updating single ActionPlan
    public int updateActionPlan(ActionPlan actionPlan) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {        // updating row
            return db.update(TABLE_ACTION_PLAN, actionPlan.getContentValues(), KEY_AP_ID + " = ?",
                    new String[]{String.valueOf(actionPlan.get_id())});
        } finally {
            db.close();
        }
    }

    // Deleting single FEReport
    public void deleteFEReport(FEReport feReport) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            db.delete(TABLE_FE_REPORT, KEY_FE_ID + " = ?",
                    new String[]{String.valueOf(feReport.get_id())});
        } finally {
            db.close();
        }
    }

    // Deleting single ActionPlan
    public void deleteActionPlan(ActionPlan actionPlan) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            db.delete(TABLE_ACTION_PLAN, KEY_AP_ID + " = ?",
                    new String[]{String.valueOf(actionPlan.get_id())});
        } finally {
            db.close();
        }
    }

    // Getting ActionPlan Count
    public int getActionPlanCount() {
        String countQuery = "SELECT  * FROM " + TABLE_ACTION_PLAN;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
        // return count
        return cursor.getCount();
    }

    // Getting FEReport Count
    public int getFEReportCount() {
        String countQuery = "SELECT  * FROM " + TABLE_FE_REPORT;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
        // return count
        return cursor.getCount();
    }

    public ActionPlan getLatestActionPlan() {
        SQLiteDatabase db = this.getReadableDatabase();
        Log.i(TAG, "DB init over. querying the db now.");
        Cursor cursor = db.query(TABLE_ACTION_PLAN, new String[]{KEY_AP_ID,
                        KEY_AP_TICKET_ID, KEY_AP_ACTION_ID, KEY_AP_NAME,
                        KEY_AP_WWSTART, KEY_AP_ACTION_PLAN,
                        KEY_AP_SITE_CONTACT, KEY_AP_SITE_ACCESS, KEY_FE_REPORT_CREATED, KEY_AP_ORDER}, KEY_FE_REPORT_CREATED + "=?",
                new String[]{String.valueOf(false)}, null, null, KEY_AP_ORDER + " ASC", null
        );
        if (cursor != null && cursor.getCount() != 0) {
            Log.i(TAG, "Cursor is not null and it count of rows fetched are also not zero. ");
            cursor.moveToFirst();
            try {
                Log.i(TAG, "Going to form Action plan ");
                return formActionPlan(cursor);
            } finally {
                cursor.close();
            }
        }
        Log.i(TAG, "Cursor is empty");
        try {
            return null;
        } finally {
            cursor.close();
        }
    }

    public Location getLocation(Location location) {
        SQLiteDatabase db = this.getReadableDatabase();
        Log.i(TAG, "Created a db instance. now querying the db");
        Cursor cursor = db.query(TABLE_LOCATION, new String[]{KEY_LOCATION_ID,
                        KEY_LOCATION_LOC_ID, KEY_LOCATION_NAME, KEY_LOCATION_VERSION}, KEY_LOCATION_LOC_ID + "=? AND " + KEY_LOCATION_NAME + "=?",
                new String[]{location.getLocationId(), location.getLocation()}, null, null, null, null
        );
        Log.i(TAG, "Got Cursor from db query.");
        if (cursor != null && cursor.getCount() != 0) {
            Log.i(TAG, "Cursor not null. moving the cursor to first row");
            cursor.moveToFirst();
            Log.i(TAG, "Creating a Location and setting primary id in parameter location");
            location.set_id(formLocation(cursor).get_id());
            Log.i(TAG, "Parameter location id is set.");
        }
        try {
            return location;
        } finally {
            cursor.close();
        }
    }

    private Location formLocation(Cursor cursor) {
        Log.i(TAG, "Cursor :" + cursor);
        if (cursor == null || cursor.getCount() == 0) {
            Log.i(TAG, "Cursor is NULL or count is not ZERO.");
            return null;
        }
        Log.i(TAG, "Cursor is not null and count is not zero.");
        return new Location(cursor.getLong(0),
                cursor.getString(1),
                cursor.getString(2),
                cursor.getLong(3));
    }

    public Location saveLocation(Location location) {
        SQLiteDatabase db = this.getWritableDatabase();
        // Inserting Row
        long id = db.insert(TABLE_LOCATION, null, location.getContentValues());
        db.close(); // Closing database connection
        location.set_id(id);
        return location;
    }

    // Updating single Location
    public Location updateLocation(Location location) {
        SQLiteDatabase db = this.getWritableDatabase();

        // updating row
        db.update(TABLE_LOCATION, location.getContentValues(), KEY_LOCATION_ID + " = ?",
                new String[]{String.valueOf(location.get_id())});
        try {
            return location;
        } finally {
            db.close();
        }
    }

    public Part getPart(Part part) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_PART, new String[]{KEY_PART_ID,
                        KEY_PART_PART_ID, KEY_PART_NAME}, KEY_PART_PART_ID + "=? AND " + KEY_PART_NAME + "=?",
                new String[]{part.getPartId(), part.getPart()}, null, null, null, null
        );
        if (cursor != null && cursor.getCount() != 0) {
            cursor.moveToFirst();
            part.set_id(formPart(cursor).get_id());
        }
        db.close(); // Closing database connection
        return part;
    }

    private Part formPart(Cursor cursor) {
        if (cursor == null || cursor.getCount() == 0) return null;
        return new Part(cursor.getLong(0),
                cursor.getString(1),
                cursor.getString(2));
    }

    public Part savePart(Part part) {
        SQLiteDatabase db = this.getWritableDatabase();
        // Inserting Row
        long id = db.insert(TABLE_PART, null, part.getContentValues());
        db.close(); // Closing database connection
        part.set_id(id);
        return part;
    }

    public void saveLocationPart(LocationPart locationPart) {
        SQLiteDatabase db = this.getWritableDatabase();
        // Inserting Row
        long id = db.insert(TABLE_LOCATION_PART, null, locationPart.getContentValues());
        db.close(); // Closing database connection
    }

    public int getQuantity(String part, String location) {
        String countQuery = "SELECT  lp." + KEY_LOCATION_PART_QUANTITY + " FROM " + TABLE_LOCATION_PART + " lp LEFT JOIN  "
                + TABLE_PART + " p ON lp." + KEY_LOCATION_PART_PART_ID + "=p." + KEY_PART_ID + " LEFT JOIN "
                + TABLE_LOCATION + " l ON  lp." + KEY_LOCATION_PART_LOC_ID + "=l." + KEY_LOCATION_ID + " where p."
                + KEY_PART_NAME + "=\"" + part + "\" and l." + KEY_LOCATION_NAME + "=\"" + location
                + "\" ";
        Log.i(TAG, "QUERY for Total quantity is :" + countQuery);
        Cursor cursor = null;
        try {
            SQLiteDatabase db = this.getReadableDatabase();
            cursor = db.rawQuery(countQuery, null);
            if (cursor != null && cursor.getCount() != 0) {
                cursor.moveToFirst();
                return cursor.getInt(0);
            }
        } finally {
            if (cursor != null) cursor.close();
        }
        return 0;
    }

    public List<FEReport> getAllFEReportsPending(Context context) {
        List<FEReport> feReportsList = new ArrayList<FEReport>();
        // Select All Query
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_FE_REPORT, new String[]{KEY_FE_ID, KEY_FE_TICKET_ID, KEY_FE_ACTION_PLAN,
                        KEY_FE_FIELD_ENGINEER_ID, KEY_FE_WORK_WINDOW, KEY_FE_TIME_START, KEY_FE_TIME_FINISHED,
                        KEY_FE_WORK_DONE, KEY_FE_BILLABLE, KEY_FE_CLOSED, KEY_FE_TIME_TRAVEL,
                        KEY_FE_MILES, KEY_FE_NUMBER_01, KEY_FE_PART_01, KEY_FE_LOCATION_01, KEY_FE_NUMBER_02,
                        KEY_FE_PART_02, KEY_FE_LOCATION_02, KEY_FE_NUMBER_03, KEY_FE_PART_03, KEY_FE_LOCATION_03,
                        KEY_FE_NUMBER_04, KEY_FE_PART_04, KEY_FE_LOCATION_04, KEY_FE_SENT}, KEY_FE_SENT + "=?",
                new String[]{String.valueOf(false)}, null, null, null, null
        );
        if (cursor != null && cursor.getCount() != 0) {
            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    feReportsList.add(formFEReport(cursor));
                } while (cursor.moveToNext());
            }
        }
        try {
            return feReportsList;
        } finally {
            cursor.close();
        }
    }

    public Part getPartByName(String part_name) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_PART, new String[]{KEY_PART_ID,
                        KEY_PART_PART_ID, KEY_PART_NAME}, KEY_PART_NAME + "=?",
                new String[]{part_name}, null, null, null, null
        );
        if (cursor != null && cursor.getCount() != 0) {
            cursor.moveToFirst();
            try {
                return formPart(cursor);
            } finally {
                cursor.close();
                db.close();
            }
        }
        try {
            return null;
        } finally {
            cursor.close();
            db.close();
        }
    }

    public Location getLocationByName(String location_name) {
        SQLiteDatabase db = this.getReadableDatabase();
        Log.i(TAG, "Created a db instance. now querying the db");
        Cursor cursor = db.query(TABLE_LOCATION, new String[]{KEY_LOCATION_ID,
                        KEY_LOCATION_LOC_ID, KEY_LOCATION_NAME, KEY_LOCATION_VERSION}, KEY_LOCATION_NAME + "=?",
                new String[]{location_name}, null, null, null, null
        );
        Log.i(TAG, "Got Cursor from db query.");
        if (cursor != null && cursor.getCount() != 0) {
            Log.i(TAG, "Cursor not null. moving the cursor to first row");
            cursor.moveToFirst();
            Log.i(TAG, "Creating a Location and setting primary id in parameter location");
            try {
                return formLocation(cursor);
            } finally {
                cursor.close();
                db.close();
            }
        }
        try {
            return null;
        } finally {
            cursor.close();
            db.close();
        }
    }
}
